﻿
using BLL;
using DAL;
using Model;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Tools;
using static System.Collections.Specialized.BitVector32;

namespace 校准综测
{
    public partial class JZZCForm : Form
    {
        private SimbaBLL simbaBLL = new SimbaBLL();
        private AppHelper app = new AppHelper();
        private ConfigHelper configHelper = new ConfigHelper();
        private SerialPort boxPort1 = new SerialPort();
        private JZZCSetting set = null;
        private SerialPort boxPort2 = new SerialPort();
        private string setPath = System.Environment.CurrentDirectory + "\\Setting.config";
        private ML302DAL mL302DAL = new ML302DAL();
        private PortBLL portBLL = null;
        private JZZCFormBLL formBLL = new JZZCFormBLL();
        private Dictionary<string, string> dic = new Dictionary<string, string>();
        private UIBLL uIBLL = new UIBLL();
        private string snimei1 = "";
        private string snimei2 = "";
        private string result1 = "ng";
        private string result2 = "ng";
        public string csj1 = "";
        public string csj2 = "";
        Thread jzzc1 = null;
        Thread jzzc2 = null;
        private string realy = "";
        SerialPort port = new SerialPort();
        private bool shouldClear = true;
        //用充当数据接收缓冲
        private List<byte> receivedata = new List<byte>();
        public JZZCForm()
        {
            InitializeComponent();
            //timer1.Start();
        }
        #region 鼠标
        //private void GetMousePoint()
        //{
        //    Point ms = Control.MousePosition;
        //    this.label2.Text = string.Format("当前鼠标位置：{0}:{1}", ms.X, ms.Y);
        //    MouseButtons mb = Control.MouseButtons;

        //}
        ////更新鼠标位置等信息。
        //private void timer1_Tick(object sender, EventArgs e)
        //{
        //    GetMousePoint();
        //}
        #endregion
        public void PortInit()
        {
            comboBoxBoxPort1.Items.Clear();
            comboBoxBoxPort1.Items.AddRange(SerialPort.GetPortNames());
            comboBoxBoxPort2.Items.Clear();
            comboBoxBoxPort2.Items.AddRange(SerialPort.GetPortNames());
            if (set.box1Port == set.box2Port)
            {
                labelMes.Text = "串口配置错误！";
                return;
            }
            if (comboBoxBoxPort1.Items.Contains(set.box1Port))
            {
                if (!boxPort1.IsOpen)
                {
                    portBLL.OpenPort(boxPort1, set.box1Port, 115200);
                    comboBoxBoxPort1.Text = set.box1Port;
                    if (boxPort1.IsOpen)
                    {
                        portBLL.SendData(boxPort1, PortModel.ClearData);
                    }
                }
            }
            if (comboBoxBoxPort2.Items.Contains(set.box2Port))
            {
                if (!boxPort2.IsOpen)
                {
                    portBLL.OpenPort(boxPort2, set.box2Port, 115200);
                    comboBoxBoxPort2.Text = set.box2Port;
                    if (boxPort2.IsOpen)
                    {
                        portBLL.SendData(boxPort2, PortModel.ClearData);
                    }
                }
            }
        }
        private void JZZCForm_Load(object sender, System.EventArgs e)
        {

            bool isOk = new Sql().SqlCheck();
            if (isOk == false)
            {
                MessageBox.Show("服务器连接异常！");
                this.Close();
                System.Environment.Exit(0);
            }
            this.Visible = false;
            dic = configHelper.ReadAll(setPath);
            set = new JZZCSetting(dic);
            string logPath = set.simbaLogPath;
            DirectoryInfo theFolder = new DirectoryInfo(logPath);
            DirectoryInfo[] dirInfos = theFolder.GetDirectories();
            theFolder = dirInfos[0];
            foreach (var item in dirInfos)
            {
                if (item.LastWriteTime > theFolder.LastWriteTime)
                {
                    theFolder = item;
                }
            }
            labelStation.Text = set.stationcode;
            labelBox1.Text = set.box1;
            label3.Text = set.box1 + "串口";
            labelBox2.Text = set.box2;
            label1.Text = set.box2 + "串口";
            portBLL = new PortBLL(textBoxRec,labelMes);
            app.GetAPP(this, panel1, "校准综测", dic);
            AppHelper.Delay(1000);
           //app.MouseClick(PointModel.Simba_JZZC.MaxWindow);
           // AppHelper.Delay(200);
            tabPage1.Focus();
            panel1.Focus();
            PortInit();
        }
        private void radioButtonManual_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonManual.Checked == true)
            {
                if (jzzc1 != null)
                {
                    jzzc1.Abort();
                    AppHelper.Delay(200);
                    jzzc1 = null;
                }
                if (jzzc2 != null)
                {
                    jzzc2.Abort();
                    AppHelper.Delay(200);
                    jzzc2 = null;
                }
                btnStart1.BackColor = tabPage1.BackColor;
                btnCode1.BackColor = tabPage1.BackColor;
                btnWrite1.BackColor = tabPage1.BackColor;
                btnTake1.BackColor = tabPage1.BackColor;
                btnTake1.Enabled = true;
                btnCode1.Enabled = true;
                btnWrite1.Enabled = true;
                btnStart1.Enabled = true;
                btnStart2.BackColor = tabPage1.BackColor;
                btnCode2.BackColor = tabPage1.BackColor;
                btnWrite2.BackColor = tabPage1.BackColor;
                btnTake2.BackColor = tabPage1.BackColor;
                btnTake2.Enabled = true;
                btnCode2.Enabled = true;
                btnWrite2.Enabled = true;
                btnStart2.Enabled = true;
            }
        }
        private void radioButtonAuto_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonAuto.Checked == true && jzzc1 == null && jzzc2 == null)
            {
                btnStart1.BackColor = tabPage1.BackColor;
                btnCode1.BackColor = tabPage1.BackColor;
                btnWrite1.BackColor = tabPage1.BackColor;
                btnTake1.BackColor = tabPage1.BackColor;
                btnTake1.Enabled = false;
                btnCode1.Enabled = false;
                btnWrite1.Enabled = false;
                btnStart1.Enabled = true;
                btnStart2.BackColor = tabPage1.BackColor;
                btnCode2.BackColor = tabPage1.BackColor;
                btnWrite2.BackColor = tabPage1.BackColor;
                btnTake2.BackColor = tabPage1.BackColor;
                btnTake2.Enabled = false;
                btnCode2.Enabled = false;
                btnWrite2.Enabled = false;
                btnStart2.Enabled = true;
            }
        }
        private void labelMes_TextChanged(object sender, System.EventArgs e)
        {
            if (labelMes.Text.Contains("！") || labelMes.Text.Contains("!"))
            {
                labelMes.ForeColor = Color.Red;
            }
            else
            {
                labelMes.ForeColor = Color.Black;
            }
        }

        private void comboBoxBoxPort_DropDown(object sender, System.EventArgs e)
        {
            if ((sender as ComboBox).Name == comboBoxBoxPort1.Name)
            {
                comboBoxBoxPort1.Items.Clear();
                comboBoxBoxPort1.Items.AddRange(SerialPort.GetPortNames());
            }
            if ((sender as ComboBox).Name == comboBoxBoxPort2.Name)
            {
                comboBoxBoxPort2.Items.Clear();
                comboBoxBoxPort2.Items.AddRange(SerialPort.GetPortNames());
            }
        }

        private void comboBoxBoxPort_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            if ((sender as ComboBox).Name == comboBoxBoxPort1.Name)
            {
                if (boxPort1.IsOpen)
                {
                    boxPort1.Close();
                }
                if (comboBoxBoxPort1.Text != "")
                {
                    portBLL.OpenPort(boxPort1, comboBoxBoxPort1.Text, 115200);
                }
                if (comboBoxBoxPort1.Text != set.box1Port)
                {
                    set.box1Port = comboBoxBoxPort1.Text;
                    configHelper.Write(setPath, "box1Port", set.box1Port);
                    dic["box1Port"] = set.box1Port;
                }
            }
            if ((sender as ComboBox).Name == comboBoxBoxPort2.Name)
            {
                if (boxPort2.IsOpen)
                {
                    boxPort2.Close();
                }
                if (comboBoxBoxPort2.Text != "")
                {
                    portBLL.OpenPort(boxPort2, comboBoxBoxPort2.Text, 115200);
                }
                if (comboBoxBoxPort2.Text != set.box2Port)
                {
                    set.box2Port = comboBoxBoxPort2.Text;
                    configHelper.Write(setPath, "box2Port", set.box2Port);
                    dic["box2Port"] = set.box2Port;
                }
            }
        }

        private void buttonReset_Click(object sender, System.EventArgs e)
        {
            if ((sender as Button).Name == buttonReset1.Name)
            {
                if (boxPort1.IsOpen)
                {
                    portBLL.SendData(boxPort1, PortModel.InitRobot);
                }
            }
            if ((sender as Button).Name == buttonReset2.Name)
            {
                if (boxPort2.IsOpen)
                {
                    portBLL.SendData(boxPort2, PortModel.InitRobot);
                }
            }
        }

        private void buttonClearDate_Click(object sender, System.EventArgs e)
        {
            if ((sender as Button).Name == buttonClearDate1.Name)
            {
                if (boxPort1.IsOpen)
                {
                    portBLL.SendData(boxPort1, PortModel.ClearData);
                }
            }
            if ((sender as Button).Name == buttonClearDate2.Name)
            {
                if (boxPort2.IsOpen)
                {
                    portBLL.SendData(boxPort2, PortModel.ClearData);
                }
            }
        }

        private void buttonPut_Click(object sender, System.EventArgs e)
        {
            if ((sender as Button).Name == buttonPut1.Name)
            {
                if (boxPort1.IsOpen)
                {
                    portBLL.SendData(boxPort1, PortModel.OpenBox);
                    portBLL.SendData(boxPort1, PortModel.PlacePCB);
                }
            }
            if ((sender as Button).Name == buttonPut2.Name)
            {
                if (boxPort2.IsOpen)
                {
                    portBLL.SendData(boxPort2, PortModel.OpenBox);
                    portBLL.SendData(boxPort2, PortModel.PlacePCB);
                }
            }
        }

        private void buttonCode_Click(object sender, System.EventArgs e)
        {
            if ((sender as Button).Name == buttonCode1.Name)
            {
                if (boxPort1.IsOpen)
                {
                    portBLL.SendData(boxPort1, PortModel.GetCode);
                }
            }
            if ((sender as Button).Name == buttonCode2.Name)
            {
                if (boxPort2.IsOpen)
                {
                    portBLL.SendData(boxPort2, PortModel.GetCode);
                }
            }
        }

        private void buttonOKTake_Click(object sender, System.EventArgs e)
        {
            if ((sender as Button).Name == buttonOKTake1.Name)
            {
                if (boxPort1.IsOpen)
                {
                    portBLL.SendData(boxPort1, PortModel.OpenBox);
                    portBLL.SendData(boxPort1, PortModel.OKresult);
                }
            }
            if ((sender as Button).Name == buttonOKTake2.Name)
            {
                if (boxPort2.IsOpen)
                {
                    portBLL.SendData(boxPort2, PortModel.OpenBox);
                    portBLL.SendData(boxPort2, PortModel.OKresult);
                }
            }
        }

        private void buttonNGTake_Click(object sender, System.EventArgs e)
        {
            if ((sender as Button).Name == buttonNGTake1.Name)
            {
                if (boxPort1.IsOpen)
                {
                    portBLL.SendData(boxPort1, PortModel.OpenBox);
                    portBLL.SendData(boxPort1, PortModel.NGResult);
                }
            }
            if ((sender as Button).Name == buttonNGTake2.Name)
            {
                if (boxPort2.IsOpen)
                {
                    portBLL.SendData(boxPort2, PortModel.OpenBox);
                    portBLL.SendData(boxPort2, PortModel.NGResult);
                }
            }
        }
        private void buttonOpen_Click(object sender, System.EventArgs e)
        {
            if ((sender as Button).Name == buttonOpen1.Name)
            {
                if (boxPort1.IsOpen)
                {
                    portBLL.SendData(boxPort1, PortModel.OpenBox);
                }
            }
            if ((sender as Button).Name == buttonOpen2.Name)
            {
                if (boxPort2.IsOpen)
                {
                    portBLL.SendData(boxPort2, PortModel.OpenBox);
                }
            }
        }

        private void buttonClose_Click(object sender, System.EventArgs e)
        {
            if ((sender as Button).Name == buttonClose1.Name)
            {
                if (boxPort1.IsOpen)
                {
                    portBLL.SendData(boxPort1, PortModel.CloseBox);
                }
            }
            if ((sender as Button).Name == buttonClose2.Name)
            {
                if (boxPort2.IsOpen)
                {
                    portBLL.SendData(boxPort2, PortModel.CloseBox);
                }
            }
        }

        private void buttonSend_Click(object sender, System.EventArgs e)
        {
            if (boxPort1.IsOpen && radioButtonBox1.Checked == true)
            {
                string str = textBoxSend.Text;
                portBLL.SendData(boxPort1, str);
            }
            if (boxPort2.IsOpen && radioButtonBox2.Checked == true)
            {
                string str = textBoxSend.Text;
                portBLL.SendData(boxPort2, str);
            }
        }

        private void JZZCForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            System.Environment.Exit(0);
        }

        #region 方法
        public void Place(SerialPort boxPort, Button button1, Button button2, string station)
        {
            uIBLL.SetButton(button1, Color.Gold, false);

            uIBLL.LabelShowMsg(labelMes, station + "关闭电源");
            if (!portBLL.SendData(boxPort, PortModel.ZCPowerOFF).Trim().Contains(PortModel.ZCPowerOFFOk))
            {
                uIBLL.SetButton(button1, Color.Red, true);
                uIBLL.LabelShowMsg(labelMes, station + "关闭电源失败！");
                return;
            }
            uIBLL.LabelShowMsg(labelMes, station + "打开");
            if (!portBLL.SendData(boxPort, PortModel.OpenBox).Trim().Contains(PortModel.OpenBoxOk))
            {
                uIBLL.SetButton(button1, Color.Red, true);
                uIBLL.LabelShowMsg(labelMes, station + "打开失败！");
                return;
            }
            uIBLL.LabelShowMsg(labelMes, station + "请求放板");
            if (!portBLL.SendData(boxPort, PortModel.PlacePCB).Trim().Contains(PortModel.PlacePCBOk))
            {
                uIBLL.SetButton(button1, Color.Red, true);
                uIBLL.LabelShowMsg(labelMes, station + "请求放板失败！");
                return;
            }
            uIBLL.LabelShowMsg(labelMes, station + "放板完成");
            uIBLL.SetButton(button1, Color.ForestGreen, false);
            uIBLL.SetButton(button2, tabPage1.BackColor, true);
            AppHelper.Delay(10);
        }
        public void GetCode(SerialPort boxPort, Button button1, Button button2, string station)
        {
            uIBLL.SetButton(button1, Color.Gold, false);
            uIBLL.LabelShowMsg(labelMes, station + "获取条码");
            if (station == set.box1)
            {
                string[] code = portBLL.SendData(boxPort, PortModel.GetCode).Split(';');
                snimei1 = (code[1] + ";" + code[2]).ToUpper();
                //todo: 过站确认
                if (snimei1.Length != 36)
                {
                    uIBLL.SetButton(button1, Color.Red, true);
                    uIBLL.LabelShowMsg(labelMes, station + "条码错误！");
                    return;
                }
            }
            else
            {
                string[] code = portBLL.SendData(boxPort, PortModel.GetCode).Split(';');
                snimei2 = (code[1] + ";" + code[2]).ToUpper();
                //todo: 过站确认
                if (snimei2.Length != 36)
                {
                    uIBLL.SetButton(button1, Color.Red, true);
                    uIBLL.LabelShowMsg(labelMes, station + "条码错误！");
                    return;
                }
            }
            uIBLL.LabelShowMsg(labelMes, station + "获取条码完成");
            uIBLL.SetButton(button1, Color.ForestGreen, false);
            uIBLL.SetButton(button2, tabPage1.BackColor, true);
            AppHelper.Delay(10);
        }
        public string Write1(string code)
        {
            string result = PortModel.OKresult;
            string sn1 = GetBack(code, "FUNC:IMP?\r\n\r\n");
            if (sn1!="OK")
            {
                result= PortModel.NGResult;
                return result;
            }
            string sn2 = GetBack(code, "FUNC:IMP?\r\n\r\n");
            if (sn2 != "OK")
            {
                result = PortModel.NGResult;
                return result;
            }
            return PortModel.OKresult;
        }
        public string GetBack(string code, string order)
        {
            realy = "";
            string ckname = code;
            if (port.IsOpen)
            {
                port.Close();
            }
            port.PortName = ckname;
            port.BaudRate = 9600;
            port.Open();
            serialport();
            Encoding gb = System.Text.Encoding.GetEncoding("gb2312");
            byte[] bytes = gb.GetBytes(order);
            port.Write(bytes, 0, bytes.Length);
            //realy = port.ReadLine();
            while (realy == "")
            {
                System.Threading.Thread.Sleep(1000);
            }
            return realy;
        }
        private void serialport()
        {
            port.DataReceived += Serialport_receData;
        }
        private void Serialport_receData(object sender, SerialDataReceivedEventArgs e)
        {
            System.Threading.Thread.Sleep(100);
            //获取当前接收数据的串口
            SerialPort sp = sender as SerialPort;
            if (sp.IsOpen)//串口是打开的
            {
                int byteread = sp.BytesToRead;//获取接收缓冲区中数据的字节数。
                byte[] readdata = new byte[byteread];
                sp.Read(readdata, 0, byteread);//读串口，将数据存到字节型数组。
                if (shouldClear == true)
                {
                    receivedata.Clear();
                    shouldClear = false;//接下来会使用缓冲区，防止缓冲区被意外清空
                }
                //暂存缓冲区字节到全局缓冲区中等待处理
                receivedata.AddRange(readdata);
                //缓冲区达到字节阈值
                int endone = receivedata.Count - 1;
                if (receivedata[endone] == 0x0A)
                {
                    port.Close();
                    List<byte> recveivdata = new List<byte>();
                    recveivdata.AddRange(receivedata);
                    if (recveivdata.Count == 0)
                    {
                        return;
                    }

                    realy = BytesToText(recveivdata, Encoding.GetEncoding("GB2312"));
                    shouldClear = true;
                }
            }
        }
        public static string BytesToText(List<byte> bytesBuffer, Encoding encoding)
        {
            return encoding.GetString(bytesBuffer.ToArray<byte>());
        }
        public string Write(SerialPort boxPort, Button button1, Button button2, string station,bool firstTime)
        {
            string result = PortModel.NGResult;
            uIBLL.SetButton(button1, Color.Gold, false);
            uIBLL.LabelShowMsg(labelMes, station + "校准综测");
            dic = configHelper.ReadAll(setPath);
            int delay = int.Parse(dic["closedelay"]);


            if (station == set.box1)
            {
             
                DirectoryInfo baseFolder = new DirectoryInfo(set.simbaLogPath);
                DirectoryInfo[] dirInfos = baseFolder.GetDirectories();
                // baseFolder = dirInfos[0];
                //foreach (var item in dirInfos)
                //{
                //    if (item.LastWriteTime > baseFolder.LastWriteTime)
                //    {
                //        baseFolder = item;
                //    }
                //}
                //读取log文件
                //string logPath = baseFolder.FullName + "\\" + "DUT0" + "\\" + DateTime.Now.ToString("yyyyMMdd");
                //string logPath = baseFolder.FullName + "\\" + "CH1";
                //DirectoryInfo logFolder = new DirectoryInfo(logPath);
                string logPath = baseFolder.FullName;
                AppHelper.Delay(10);
                uIBLL.LabelShowMsg(labelMes, station + "关闭");
                if (portBLL.SendData(boxPort, PortModel.CloseBox).Trim() != PortModel.CloseBoxOk)
                {
                    uIBLL.SetButton(button1, Color.Red, true);
                    uIBLL.LabelShowMsg(labelMes, station + "关闭失败！");
                    return result;
                }
                AppHelper.Delay(delay);
                uIBLL.LabelShowMsg(labelMes, station + "打开电源");
                if (!portBLL.SendData(boxPort, PortModel.ZCPowerON).Trim().Contains(PortModel.ZCPowerONOk))
                {
                    uIBLL.SetButton(button1, Color.Red, true);
                    uIBLL.LabelShowMsg(labelMes, station + "打开电源失败！");
                    return result;
                }
                //app.MouseClick(PointModel.Simba_JZZC.Start1);
                AppHelper.Delay(500);
                //app.MouseClick(PointModel.Simba_JZZC.Start1);
                LogHelper.WriteDebugLog(set.simbaLogPath + "  wanl  " );
                result = formBLL.GetReslut(set.simbaLogPath, snimei1, "CH1", station, portBLL, boxPort, app, firstTime, set.devcode1);
                if (result == "two")
                {
                    app.MouseClick(PointModel.Simba_JZZC.Start1);
                    result = formBLL.GetReslut(set.simbaLogPath, snimei1, "CH1", station, portBLL, boxPort, app, firstTime, set.devcode1);
                }
            } 
            else
            {
              
                DirectoryInfo baseFolder = new DirectoryInfo(set.simbaLogPath);
                DirectoryInfo[] dirInfos = baseFolder.GetDirectories();
                //baseFolder = dirInfos[0];
                //foreach (var item in dirInfos)
                //{
                //    if (item.LastWriteTime > baseFolder.LastWriteTime)
                //    {
                //        baseFolder = item;
                //    }
                //}
                //string logPath = baseFolder.FullName + "\\" + "DUT1" + "\\" + DateTime.Now.ToString("yyyyMMdd");
                //string logPath = baseFolder.FullName + "\\" + "CH2";
                string logPath = baseFolder.FullName;
                DirectoryInfo logFolder = new DirectoryInfo(logPath);
                AppHelper.Delay(10);
                uIBLL.LabelShowMsg(labelMes, station + "关闭");
                if (portBLL.SendData(boxPort, PortModel.CloseBox).Trim() != PortModel.CloseBoxOk)
                {
                    uIBLL.SetButton(button1, Color.Red, true);
                    uIBLL.LabelShowMsg(labelMes, station + "关闭失败！");
                    return result;
                }
                AppHelper.Delay(delay);
                uIBLL.LabelShowMsg(labelMes, station + "打开电源");
                if (!portBLL.SendData(boxPort, PortModel.ZCPowerON).Trim().Contains(PortModel.ZCPowerONOk))
                {
                    uIBLL.SetButton(button1, Color.Red, true);
                    uIBLL.LabelShowMsg(labelMes, station + "打开电源失败！");
                    return result;
                }
                //app.MouseClick(PointModel.Simba_JZZC.Start2);
                AppHelper.Delay(500);
                //app.MouseClick(PointModel.Simba_JZZC.Start2);
                result = formBLL.GetReslut(set.simbaLogPath, snimei2, "CH2", station, portBLL, boxPort, app, firstTime, set.devcode2);
                if (result == "two")
                {
                    app.MouseClick(PointModel.Simba_JZZC.Start2);
                    result = formBLL.GetReslut(set.simbaLogPath, snimei2, "CH2", station, portBLL, boxPort, app, firstTime, set.devcode2);
                }
            }
            uIBLL.LabelShowMsg(labelMes, station + "校准综测完成");
            uIBLL.SetButton(button1, Color.ForestGreen, false);
            uIBLL.SetButton(button2, tabPage1.BackColor, true);
            //if (formBLL.Upload(snimei2, result2, set.devcode2, labelMes) == "NG")
            //    result2 = PortModel.NGResult;
            AppHelper.Delay(10);
            return result;

        }
        
        public void Take(SerialPort boxPort, Button button1, Button button2, string station, string result, string Sn)
        {
            uIBLL.SetButton(button1, Color.Gold, false);
            uIBLL.LabelShowMsg(labelMes, station + "关闭电源");
            if (!portBLL.SendData(boxPort, PortModel.ZCPowerOFF).Trim().Contains(PortModel.ZCPowerOFFOk))
            {
                uIBLL.SetButton(button1, Color.Red, true);
                uIBLL.LabelShowMsg(labelMes, station + "关闭电源失败！");
                return;
            }
            uIBLL.LabelShowMsg(labelMes, station + "打开");
            if (portBLL.SendData(boxPort, PortModel.OpenBox).Trim() != PortModel.OpenBoxOk)
            {
                uIBLL.SetButton(button1, Color.Red, true);
                uIBLL.LabelShowMsg(labelMes, station + "打开失败！");
                return;
            }
            //todo

            uIBLL.LabelShowMsg(labelMes, station + "取板");
            if (!portBLL.SendData(boxPort, result).Trim().Contains(PortModel.TakeOk))
            {
                uIBLL.SetButton(button1, Color.Red, true);
                uIBLL.LabelShowMsg(labelMes, station + "取板失败！");
                return;
            }
            //传入数据到上位机
            if (Sn.ToString().Trim().Length > 1)
            {
                if (!portBLL.SendData(boxPort, Sn).Trim().Contains("ok"))
                {
                    uIBLL.LabelShowMsg(labelMes, station + "传入数据失败！" + Sn);

                }
            }
            uIBLL.LabelShowMsg(labelMes, station + "取板完成");
            uIBLL.SetButton(button1, Color.ForestGreen, false);
            AppHelper.Delay(10);
        }
        #endregion
        private void ReturnCount(SerialPort port)
        {
            string count = mL302DAL.GetSysTestCount();

            LogHelper.WritePortLog("夹具OK数量" + ":" + count);
            if (count!="err")
            {
                portBLL.SendData(port, count);
            }
        }

        private void btnCode_Click(object sender, System.EventArgs e)
        {
            if ((sender as Button).Name == btnCode1.Name)
            {
                GetCode(boxPort1, btnCode1, btnWrite1, set.box1);
            }
            if ((sender as Button).Name == btnCode2.Name)
            {
                GetCode(boxPort2, btnCode2, btnWrite2, set.box2);
            }
        }
        private void btnWrite_Click(object sender, System.EventArgs e)
        {
            if ((sender as Button).Name == btnWrite1.Name)
            {
                result1 = Write(boxPort1, btnWrite1, btnTake1, set.box1,true);
            }
            if ((sender as Button).Name == btnWrite2.Name)
            {
                result2 = Write(boxPort2, btnWrite2, btnTake2, set.box2,true);
            }
        }

        private void btnTake_Click(object sender, System.EventArgs e)
        {
            if ((sender as Button).Name == btnTake1.Name)
            {
                Take(boxPort1, btnTake1, btnStart1, set.box1, result1, csj1);
            }
            if ((sender as Button).Name == btnTake2.Name)
            {
                Take(boxPort2, btnTake2, btnStart2, set.box2, result2, csj2);
            }

        }
        private delegate void invokehandler();
        bool DUT1first = true;
        bool DUT2first = true;
        private void thread1()
        {

            portBLL.SendData(boxPort1, PortModel.ClearData);
            while (true)
            {

                uIBLL.SetButton(btnStart1, tabPage1.BackColor, true);
                uIBLL.SetButton(btnCode1, tabPage1.BackColor, false);
                uIBLL.SetButton(btnWrite1, tabPage1.BackColor, false);
                uIBLL.SetButton(btnTake1, tabPage1.BackColor, false);
                Place(boxPort1, btnStart1, btnWrite1, set.box1);
                if (btnStart1.BackColor == Color.Red)
                {
                    DUT1first = true;
                    return;
                }
                GetCode(boxPort1, btnCode1, btnWrite1, set.box1);
                if (btnCode1.BackColor == Color.Red)
                {
                    Take(boxPort1, btnTake1, btnStart1, set.box1, PortModel.NGResult, csj1);
                    LogHelper.WriteLog(set.box1 + "#" + snimei1 + "#" + PortModel.NGResult);
                    if (btnTake1.BackColor == Color.Red)
                    {
                        DUT1first = true;
                        return;
                    }
                    DUT1first = false;
                    continue;
                }
                result1 = Write(boxPort1, btnWrite1, btnTake1, set.box1, DUT1first);
                LogHelper.WriteDebugLog(result1+"wanl");
                uIBLL.LabelShowMsg(label5, result1);
                DUT1first = false;
                if (btnWrite1.BackColor == Color.Red)
                {
                    csj1 = "CSJ;" + snimei1 + ";" + set.devcode1 + ";" + "3" + ";ng";
                    Take(boxPort1, btnTake1, btnStart1, set.box1, PortModel.NGResult,csj1);
                    LogHelper.WriteLog(set.box1 + "#" + snimei1 + "#" + PortModel.NGResult);
                    if (btnTake1.BackColor == Color.Red)
                    {
                        DUT1first = true;
                        return;
                    }
                    DUT1first = false;
                    continue;
                }
                if (result1 == PortModel.ZCPowerOFF)
                {
                    DUT1first = false;
                    portBLL.SendData(boxPort1, PortModel.ZCPowerOFF);
                    continue;
                }
                if (result1 == PortModel.NGResult)
                {
                    csj1 = "CSJ;" + snimei1 + ";" + set.devcode1 + ";" + "3" + ";ng";
                }
                if (result1 == PortModel.OKresult)
                {
                    csj1 = "CSJ;" + snimei1 + ";" + set.devcode1 + ";" + "3" + ";ok";
                }
                Take(boxPort1, btnTake1, btnStart1, set.box1, result1, csj1);
                if (btnTake1.BackColor == Color.Red)
                {
                    DUT1first = true;
                    return;
                }
                DUT1first = true;
                //ReturnCount(boxPort1);
                csj1 = "";
            }
        }
        private void thread2()
        {
            portBLL.SendData(boxPort2, PortModel.ClearData);
            while (true)
            {
                uIBLL.SetButton(btnStart2, tabPage1.BackColor, true);
                uIBLL.SetButton(btnCode2, tabPage1.BackColor, false);
                uIBLL.SetButton(btnWrite2, tabPage1.BackColor, false);
                uIBLL.SetButton(btnTake2, tabPage1.BackColor, false);
                Place(boxPort2, btnStart2, btnWrite2, set.box2);
                if (btnStart2.BackColor == Color.Red)
                {
                    DUT2first = true;
                    return;
                }
                GetCode(boxPort2, btnCode2, btnWrite2, set.box2);
                if (btnCode2.BackColor == Color.Red)
                {
                    Take(boxPort2, btnTake2, btnStart2, set.box2, PortModel.NGResult, csj2);
                    LogHelper.WriteLog(set.box2 + "#" + snimei2 + "#" + PortModel.NGResult);
                    if (btnTake2.BackColor == Color.Red)
                    {
                        DUT2first = true;
                        return;
                    }
                    DUT2first = false;
                    continue;
                }
                result2 = Write(boxPort2, btnWrite2, btnTake2, set.box2, DUT2first);
                
                if (btnWrite2.BackColor == Color.Red)
                {
                    csj2 = "CSJ;" + snimei2 + ";" + set.devcode2 + ";" + "3" + ";ng";
                    Take(boxPort2, btnTake2, btnStart2, set.box2, PortModel.NGResult, csj2);
                    LogHelper.WriteLog(set.box2 + "#" + snimei2 + "#" + PortModel.NGResult);
                    if (btnTake2.BackColor == Color.Red)
                    {
                        DUT2first = true;
                        return;
                    }
                    DUT2first = false;
                    continue;
                }
                if (result2 == PortModel.ZCPowerOFF)
                {
                    DUT2first = false;
                    portBLL.SendData(boxPort2, PortModel.ZCPowerOFF);
                    continue;
                }
                if (result2 == PortModel.NGResult)
                {
                    csj2 = "CSJ;" + snimei2 + ";" + set.devcode2 + ";" + "3" + ";ng";
                }
                if (result2 == PortModel.OKresult)
                {
                    csj2 = "CSJ;" + snimei2 + ";" + set.devcode2 + ";" + "3" + ";ok";
                }
                Take(boxPort2, btnTake2, btnStart2, set.box2, result2,csj2);
                LogHelper.WriteLog(set.box2 + "#" + snimei2 + "#" + result2);
                if (btnTake2.BackColor == Color.Red)
                {
                    DUT2first = true;
                    return;
                }
                DUT2first = true;
                //ReturnCount(boxPort2);
                csj2 = "";
            }
        }

        private void btnStart1_Click(object sender, EventArgs e)
        {
            if (radioButtonAuto.Checked == true)
            {
                textBoxRec.Clear();
                if (!(boxPort1.IsOpen))
                {
                    btnStart1.BackColor = Color.Red;
                    uIBLL.LabelShowMsg(labelMes, set.box1 + "串口未打开！");
                    return;
                }
                try
                {
                    if (jzzc1 == null)
                    {
                        jzzc1 = new Thread(thread1);
                        jzzc1.Start();
                    }
                }
                catch (Exception ee)
                {

                    throw;
                }

            }
        }

        private void btnStart2_Click(object sender, EventArgs e)
        {
            if (radioButtonAuto.Checked == true)
            {
                textBoxRec.Clear();
                if (!(boxPort2.IsOpen))
                {
                    btnStart2.BackColor = Color.Red;
                    uIBLL.LabelShowMsg(labelMes, set.box2 + "串口未打开！");
                    return;
                }
                try
                {
                    if (jzzc2 == null)
                    {
                        jzzc2 = new Thread(thread2);
                        jzzc2.Start();
                    }
                }
                catch (Exception ee)
                {

                    throw;
                }

            }
        }

        private void btnPowerON_Click(object sender, EventArgs e)
        {
            if ((sender as Button).Name == btnPowerON1.Name)
            {
                if (boxPort1.IsOpen)
                {
                    portBLL.SendData(boxPort1, PortModel.ZCPowerON);
                }
            }
            if ((sender as Button).Name == btnPowerON2.Name)
            {
                if (boxPort2.IsOpen)
                {
                    portBLL.SendData(boxPort2, PortModel.ZCPowerON);
                }
            }
        }

        private void btnPowerOFF_Click(object sender, EventArgs e)
        {
            if ((sender as Button).Name == btnPowerOFF1.Name)
            {
                if (boxPort1.IsOpen)
                {
                    portBLL.SendData(boxPort1, PortModel.ZCPowerOFF);
                }
            }
            if ((sender as Button).Name == btnPowerOFF2.Name)
            {
                if (boxPort2.IsOpen)
                {
                    portBLL.SendData(boxPort2, PortModel.ZCPowerOFF);
                }
            }
        }

        private void JZZCForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            System.Diagnostics.Process[] myproc = System.Diagnostics.Process.GetProcesses();
            foreach (System.Diagnostics.Process item in myproc)
            {
                if (item.ProcessName.Equals("Simba") || item.ProcessName.Contains("Electro-Test"))
                {
                    item.Kill();
                    Thread.Sleep(1000);
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            label2.Text = Control.MousePosition.X.ToString();
            label4.Text = Control.MousePosition.Y.ToString();
        }
    }
}
